<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\api\model\User as UserModel;
use app\common\utils\JsonResponse;
use think\facade\Request;
use think\facade\Db;

class User extends AdminController
{
    /**
     * 获取用户列表
     */
    public function list()
    {
        try {
            $page = Request::param('page/d', 1);
            $limit = Request::param('limit/d', 10);
            $keyword = Request::param('keyword', '');
            $status = Request::param('status', '');

            $query = Db::name('user')
                ->alias('u')
                ->leftJoin('device d', 'u.id = d.user_id')
                ->field([
                    'u.id',
                    'u.username',
                    'u.phone',
                    'u.nickname',
                    'u.avatar',
                    'u.status',
                    'u.last_login_time',
                    'u.last_login_ip',
                    'u.create_time',
                    'd.device_id',
                    'd.device_name',
                    'd.device_model',
                    'd.register_time'
                ])
                ->whereNull('u.delete_time');

            // 关键词搜索
            if ($keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->whereOr([
                        ['u.username', 'like', "%{$keyword}%"],
                        ['u.nickname', 'like', "%{$keyword}%"],
                        ['u.phone', 'like', "%{$keyword}%"],
                        ['d.device_id', 'like', "%{$keyword}%"],
                        ['d.device_name', 'like', "%{$keyword}%"]
                    ]);
                });
            }

            // 状态筛选
            if ($status !== '') {
                $query->where('u.status', intval($status));
            }

            $total = $query->count();
            $list = $query->order('u.create_time', 'desc')
                ->page($page, $limit)
                ->select()
                ->each(function($item) {
                    // 处理头像URL
                    if ($item['avatar'] && strpos($item['avatar'], 'http') === false) {
                        $item['avatar'] = env('OSS_DOMAIN') . $item['avatar'];
                    }

                    // 格式化时间
                    $item['last_login_time'] = $item['last_login_time'] ? 
                        date('Y-m-d H:i:s', $item['last_login_time']) : '';
                    $item['create_time'] = $item['create_time'] ? 
                        date('Y-m-d H:i:s', $item['create_time']) : '';
                    $item['register_time'] = $item['register_time'] ?? '';

                    // 设备信息
                    $item['device'] = $item['device_id'] ? [
                        'device_id' => $item['device_id'],
                        'device_name' => $item['device_name'],
                        'device_model' => $item['device_model'],
                        'register_time' => $item['register_time']
                    ] : null;

                    // 移除冗余字段
                    unset(
                        $item['device_id'],
                        $item['device_name'],
                        $item['device_model'],
                        $item['register_time']
                    );
                    
                    return $item;
                });

            return JsonResponse::success([
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 获取用户详情
     */
    public function detail()
    {
        try {
            $id = Request::param('id/d', 0);
            
            if ($id <= 0) {
                return JsonResponse::error('用户ID无效');
            }

            $info = Db::name('user')
                ->alias('u')
                ->leftJoin('device d', 'u.id = d.user_id')
                ->field([
                    'u.*',
                    'GROUP_CONCAT(d.id) as device_ids',
                    'GROUP_CONCAT(d.device_id) as device_numbers',
                    'GROUP_CONCAT(d.device_name) as device_names',
                    'GROUP_CONCAT(d.device_model) as device_models',
                    'GROUP_CONCAT(d.register_time) as device_register_times'
                ])
                ->where('u.id', $id)
                ->whereNull('u.delete_time')
                ->group('u.id')
                ->find();

            if (!$info) {
                return JsonResponse::error('用户不存在');
            }

            // 处理设备信息
            $devices = [];
            if ($info['device_ids']) {
                $deviceIds = explode(',', $info['device_ids']);
                $deviceNumbers = explode(',', $info['device_numbers']);
                $deviceNames = explode(',', $info['device_names']);
                $deviceModels = explode(',', $info['device_models']);
                $deviceRegisterTimes = explode(',', $info['device_register_times']);

                foreach ($deviceIds as $key => $deviceId) {
                    $devices[] = [
                        'id' => $deviceId,
                        'device_id' => $deviceNumbers[$key] ?? '',
                        'device_name' => $deviceNames[$key] ?? '',
                        'device_model' => $deviceModels[$key] ?? '',
                        'register_time' => $deviceRegisterTimes[$key] ?? ''
                    ];
                }
            }

            // 移除原始的合并字段
            unset(
                $info['device_ids'],
                $info['device_numbers'],
                $info['device_names'],
                $info['device_models'],
                $info['device_register_times']
            );

            // 添加处理后的设备信息
            $info['devices'] = $devices;

            return JsonResponse::success($info);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
} 